﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;

namespace KitBuilder.DataAccess
{
    public abstract class GenericNHibernateDAO<T> : GenericDAO<T>
    {
        private static ISessionFactory sessionFactory = null;
        private static ISession session = null; 
       // private T persistentClass;

        public GenericNHibernateDAO()
        {
           // this.persistentClass = persistentClass; 
        }
        private static void buildFactory(){
            if(sessionFactory == null){
                    Configuration cfg = new Configuration();
                    cfg.Configure("hibernate.cfg.xml");
                    cfg.AddAssembly(Assembly.GetCallingAssembly());
                    sessionFactory = cfg.BuildSessionFactory();
            }
        }

        public static ISessionFactory MySessionFactory
        {
            get
            {
                if(sessionFactory == null)
                {
                    buildFactory();
                }
                return sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            if (sessionFactory == null)
            {
                buildFactory();
            }
            return sessionFactory.OpenSession();
        }

        public static void CloseSession()
        {
            if (session != null && session.IsOpen)
            {
                session.Flush();
                session.Close();
            }
            session = null;
        }


        public abstract T FindByID(long id);
        public abstract List<T> FindAll();
        public abstract void MakePersistent(T entry);
        public abstract void MakeTransient(T entry);
        public abstract void Delete(T item);
    }
}
